import React, { useEffect, useState } from 'react';
import { PageContiner } from '@/components';
import { Spin } from 'antd';
import styles from './index.module.scss';
import ReactPlayer from 'react-player';
import { getDataById, MODULE_NAME } from './redux';
import { useSelector, useDispatch } from 'react-redux';
import { useLocation } from 'react-router-dom';
import { decodeQuery } from '@/utils';

const LiveBroadRoom: React.FC = () => {
  const [isControls, serIsControls] = useState<boolean>(false);
  const [isPlaying, setIsPlaying] = useState<boolean>(false);
  const [loading, setLoading] = useState<boolean>(true);

  const dispatch = useDispatch();
  const { search } = useLocation();
  const { id } = decodeQuery(search);
  const data = useSelector(state => state[MODULE_NAME].liveBroadData)

  useEffect(() => {
    dispatch(getDataById(id))
    return () => {
      ReactPlayer.removeCustomPlayers()
    }
  }, [])

  const onReady = () => {
    serIsControls(true);
    setIsPlaying(true);
    setLoading(false);
  }

  const onStart = () => {
    setLoading(false);
  }

  const onBuffer = () => {
    setLoading(true);
  }

  const onBufferEnd = () => {
    setLoading(false);
  }

  return (
    <PageContiner>
      <Spin wrapperClassName="global-spin--blank" spinning={loading} tip="视频缓冲中..." delay={300}>
        <div className={styles['live-broad-room__wrap']}>
          {
            <ReactPlayer
              width="100%"
              height="100%"
              onReady={onReady}
              onBuffer={onBuffer}
              onBufferEnd={onBufferEnd}
              onStart={onStart}
              controls={isControls}
              playing={isPlaying}
              pip={false}
              url={data?.url[0].src}
            />
          }
        </div>
      </Spin>
    </PageContiner>
  )
}

export default LiveBroadRoom
